#!/usr/bin/perl

use strict;

package Sleeper;

require Exporter;

our @ISA = qw(Exporter);
our @EXPORT_OK = qw(
        SleeperN
        resetTimer
        sleepN
    );

use Time::HiRes;

sub new
{
    my ($proto, $interval) = @_;

    my $class = ref($proto) || $proto;

    my $self = {};
    $self->{default_interval} = $interval || 5;

    bless $self, $class;
    $self->reset;

    return $self;
}

sub reset
{
    my $self = shift;
    $self->{last_time} = Time::HiRes::time;
}

sub sleep
{
    my ($self, $interval) = @_;

    $interval = $self->{default_interval} unless ($interval);

    my $now = Time::HiRes::time;

    my $adjusted_interval = $interval - ($now - $self->{last_time});

    $self->{last_time} += $interval;

    while ($adjusted_interval > 0) {
        my $slept_seconds = Time::HiRes::sleep($adjusted_interval);
        $adjusted_interval -= $slept_seconds;
    }
}

sub SleeperN
{
    my $_int = shift;
    my $_tLast = Time::HiRes::time;

    return sub { 
        my $now = Time::HiRes::time;
        my $adjusted_interval = $_int - ($now - $_tLast);

        $_tLast += $_int;

        while ($adjusted_interval > 0) {
            my $slept_seconds = Time::HiRes::sleep($adjusted_interval);
            $adjusted_interval -= $slept_seconds;
        }
    };
}

{
  my $_tLast = Time::HiRes::time;
  sub resetTimer { $_tLast = Time::HiRes::time; }
  sub sleepN {
      my $int = shift;
      my $now = Time::HiRes::time;       

      my $adjusted_interval = $int - ($now - $_tLast);

      $_tLast += $int;

      while ($adjusted_interval > 0) {
          my $slept_seconds = Time::HiRes::sleep($adjusted_interval);
          $adjusted_interval -= $slept_seconds;
      }
   }
} 


1;
